<template>
  <div>
    <div class="bgImg" style="display: flex;justify-content: flex-end;align-items: center;width: 100%;height: 100vh">
      <div style="width: 400px; height: 395px;margin-right: 100px;display: flex;flex-wrap: wrap;justify-content: center;align-items: flex-start">
        <div style="width: 400px; height: 360px;background: #ffffff;
        border-radius: 10px;box-shadow: 0 2px 4px #989898;z-index: 5">
          <el-form ref="loginForm" :model="user" :rules="rules" style="width: 260px; margin: 0 auto;">
            <div style="font-size: 30px;color: #30c2fe;margin: 20px auto;font-weight: bolder;
          display: flex;justify-content: center;align-items: center">
              <span>登 录</span>
            </div>
            <el-form-item prop="username">
              <el-input v-model.trim="user.username" class="inputItem" placeholder="请输入用户名"/>
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model.trim="user.password" class="inputItem" placeholder="请输入密码" show-password/>
            </el-form-item>
            <el-form-item prop="code">
              <div style="display: flex;align-items: center">
                <el-input v-model.trim="user.code" class="inputItem" placeholder="请输入验证码"
                          @keyup.enter.native="login"/>
                <span style="cursor: pointer;" @click="refreshCode">
              <Identify :identifyCode="identifyCode"></Identify>
              </span>
              </div>
            </el-form-item>
            <el-button style="width: 100%;background: #24c5ff" type="primary" @click="login">同意协议并登录</el-button>
            <el-form-item prop="agree" style="display:flex;justify-content: center;height: 30px">
              <el-checkbox v-model="user.agree">我已阅读并同意
                <el-link type="primary" @click.stop="$router.push({name:'Protocol'})">《用户协议》</el-link>
              </el-checkbox>
            </el-form-item>
          </el-form>
        </div>
        <div style="display:flex;justify-content: space-between;align-items:center;height: 35px;
            box-shadow: 0 1px 2px #7c7c7c;background: rgba(253,254,255,0.81);border-radius: 0 0 10px 10px;width: 350px; ">
          <span style="cursor: pointer; color: #30c2fe;margin-left: 20px" @click="preReset">忘记密码?</span>
          <span style="cursor: pointer; color: #30c2fe; margin-right: 20px" @click="goRegister">去注册</span>
        </div>
      </div>
    </div>

    <!-- 弹窗   -->
    <el-dialog :close-on-click-modal="false" :visible.sync="dialogFormVisible" title="忘记密码"
               width="30%">
      <el-form ref="resetForm" :model="reset" :rules="rules">
        <el-form-item label="用户名" label-width="150px" prop="username">
          <el-input v-model.trim="reset.username" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="电话" label-width="150px" prop="phone">
          <el-input v-model.trim="reset.phone" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="新密码" label-width="150px" prop="password">
          <el-input v-model.trim="reset.password" autocomplete="off" show-password style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" label-width="150px" prop="checkPwd">
          <el-input v-model.trim="reset.checkPwd" autocomplete="off" show-password style="width: 80%"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">重置</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {login, resetPwd} from "@/api/user.js"
import {resetRouter} from "@/router"
import Identify from "@/components/common/Identify"
import {setUser} from "@/utils/storage"
import {validateCaptcha, validatePassword, validateUserName} from "@/utils/validator";

export default {
  name: "Login",
  computed: {
    rules() {
      return {
        username: {required: true, trigger: 'blur',
          validator: validateUserName},
        password: {required: true, trigger: 'blur',
          validator: validatePassword},
        //图片验证码校验器,需要将用户输入值与正确值比较，所以需要在此处再包一层箭头函数，手动调用扩展参数列表的validator
        code: {required: true, trigger: 'manual',
          validator: (rule, value, callback) => validateCaptcha(value, this.identifyCode, callback, this.refreshCode)},
        agree: {required: true, trigger: 'change',
          validator: (rule,value,callback)=> !value?callback(new Error('请阅读并勾选用户协议')):callback()}
      }
    }
  },
  data() {
    return {
      reset: {},
      dialogFormVisible: false,
      user: {
        code: '',
        agree:false,
        username: '',
        password: ''
      },
      // 图片验证码
      identifyCode: '',
      // 验证码规则
      identifyCodeRule: '123456789QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm',
    }
  },
  mounted() {
    this.refreshCode()
  },
  components: {Identify},
  methods: {
    goRegister() {
      this.$router.replace("/register")
    },
    preReset() {
      this.dialogFormVisible = true
      this.reset = {}
    },
    save() {
      resetPwd(this.reset).then(res => {
        if (res.code === '0') {
          this.$message({
            type: "success",
            message: "重置成功"
          })
          this.dialogFormVisible = false
        } else {
          this.$message({
            type: "error",
            message: res.msg
          })
        }
      })
    },
    // 切换验证码
    refreshCode() {
      this.user.code = ''
      this.makeCode(4)
    },
    // 生成随机验证码
    makeCode(length) {
      this.identifyCode = ''
      for (let i = 0; i < length; i++) {
        this.identifyCode += this.identifyCodeRule[Math.floor(Math.random() * (this.identifyCodeRule.length))]
      }
    },
    login() {
      this.user.agree = true
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          login(this.user).then(res => {
            if (res.code === '0') {
              this.$message({
                type: "success",
                message: "登录成功"
              })
              setUser(res.data)
              // 重置路由
              resetRouter(JSON.parse(JSON.stringify(res.data.permission)))
              if (res.data.role.includes(1) || res.data.role.includes(3)) {
                this.$router.replace("/manage/home")
              } else {
                this.$router.replace("/front/home")
              }
            } else {
              this.refreshCode()
            }
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.bgImg {
  background: url("../assets/bg.webp") no-repeat;
  background-size: 100% 100vh;
}

::v-deep(.el-input__inner) {
  color: #000000;
  box-shadow: inset #d9d8d8 0 0 5px;
}

</style>
